############################################################################
####SEP 7, 2025--POOLED INTERACTION AND PRED PROBABILITIES ##################
#######To help with combine plotting of IVs and DVs for both years##########
library(dplyr)
library(ggplot2)
library(effects)
library(ggeffects)
library(patchwork) # for multi-panel layout

# --- STEP 1: Prepare pooled dataset (assuming you have anes_2020 and anes_2024 already cleaned in similar fashion)

anes_2020$year <- 2020
anes_2024$year <- 2024

anes_2020 <- as_tibble(anes_2020)
anes_2024 <- as_tibble(anes_2024)

# Keep only relevant variables for comparability
vars <- c("vote_choice_binary", "immigration_ideology", "rel_comp", "rel_honest", "pid", "year")

anes_pooled <- bind_rows(
  anes_2020[, vars],
  anes_2024[, vars]
)

# --- STEP 2: Pooled Model with Interactions (Option 1)
#model not sig for output but for interaction sake
model_pooled <- glm(vote_choice_binary ~ immigration_ideology * year +
                      rel_comp * year +
                      rel_honest * year +
                      pid * year,
                    data = anes_pooled,
                    family = binomial(link = "logit"),
                    na.action = na.exclude)

summary(model_pooled)

# --- STEP 3: Marginal Effects / Predicted Probabilities (Option 4)
install.packages("patchwork")
library(patchwork) # for multi-panel layout

# Immigration ideology effects by year ###to prepare for plotting
eff_immig <- allEffects(model_pooled, xlevels = list(immigration_ideology = seq(min(anes_pooled$immigration_ideology, na.rm = TRUE),
                                                                                max(anes_pooled$immigration_ideology, na.rm = TRUE),
                                                                                1)))
####HARRIS####
# Immigration ideology (1–5)
p1 <- ggpredict(model_pooled, terms = c("immigration_ideology [1:5]", "year")) %>%
  ggplot(aes(x, predicted, color = group, fill = group)) +
  geom_line(linewidth = 1.2) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2, color = NA) +
  labs(title = "Immigration Ideology",
       x = "Immigration Attitudes (1 = Liberal, 5 = Restrictive)",
       y = "Pr(Vote Biden | Harris)") +
  scale_color_manual(values = c("2020" = "blue", "2024" = "red")) +
  scale_fill_manual(values = c("2020" = "blue", "2024" = "red")) +
  theme_minimal() +
  theme(legend.position = "bottom")

# Relative Competence (1–5)
p2 <- ggpredict(model_pooled, terms = c("rel_comp [1:5]", "year")) %>%
  ggplot(aes(x, predicted, color = group, fill = group)) +
  geom_line(linewidth = 1.2) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2, color = NA) +
  labs(title = "Relative Competence (Biden/Harris – Trump)",
       x = "Competence Advantage (1 = Trump, 5 = Biden/Harris)",
       y = "Pr(Vote Biden | Harris)") +
  scale_color_manual(values = c("2020" = "blue", "2024" = "red")) +
  scale_fill_manual(values = c("2020" = "blue", "2024" = "red")) +
  theme_minimal() +
  theme(legend.position = "bottom")

# Relative Honesty (1–5)
p3 <- ggpredict(model_pooled, terms = c("rel_honest [1:5]", "year")) %>%
  ggplot(aes(x, predicted, color = group, fill = group)) +
  geom_line(linewidth = 1.2) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2, color = NA) +
  labs(title = "Relative Honesty (Biden/Harris – Trump)",
       x = "Honesty Advantage (1 = Trump, 5 = Biden/Harris)",
       y = "Pr(Vote Biden | Harris)") +
  scale_color_manual(values = c("2020" = "blue", "2024" = "red")) +
  scale_fill_manual(values = c("2020" = "blue", "2024" = "red")) +
  theme_minimal() +
  theme(legend.position = "bottom")

# PID (1–7)
p4 <- ggpredict(model_pooled, terms = c("pid [1:7]", "year")) %>%
  ggplot(aes(x, predicted, color = group, fill = group)) +
  geom_line(linewidth = 1.2) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2, color = NA) +
  labs(title = "Partisanship",
       x = "PID Scale (1 = Strong Dem, 7 = Strong Rep)",
       y = "Pr(Vote Biden | Harris)") +
  scale_color_manual(values = c("2020" = "blue", "2024" = "red")) +
  scale_fill_manual(values = c("2020" = "blue", "2024" = "red")) +
  theme_minimal() +
  theme(legend.position = "bottom")

# Combine into 2x2 grid
final_plot <- (p1 | p2) / (p3 | p4)
final_plot

# --- STEP 4: ggplot alternative (clearer visuals)

# Generate predicted probabilities with ggeffects
library(ggeffects)
preds <- ggpredict(model_pooled, terms = c("immigration_ideology", "year"))

ggplot(preds, aes(x = x, y = predicted, color = group, group = group)) +
  geom_line(size = 1.2) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group), alpha = 0.2, color = NA) +
  labs(title = "Predicted Probability of Voting Harris by Immigration Ideology",
       subtitle = "Contrast between 2020 and 2024",
       x = "Immigration Ideology (higher = more restrictive)",
       y = "Predicted Probability (Harris = 1)") +
  scale_color_manual(values = c("blue", "red")) +
  theme_minimal()


#------STEP 5: FOR TRUMP & HARRIS

library(margins)

# Average marginal effects for all predictors by year
marg_all <- margins(model_pooled, 
                    variables = c("immigration_ideology", "rel_comp", "rel_honest", "pid"),
                    at = list(year = c(2020, 2024)))
summary(marg_all)

# Compute First Differences (min → max)
library(ggeffects)

# Immigration ideology: 1 → 5
pred_immig <- ggpredict(model_pooled, terms = c("immigration_ideology [1,5]", "year"))

# Competence: 1 → 5
pred_comp <- ggpredict(model_pooled, terms = c("rel_comp [1,5]", "year"))

# Honesty: 1 → 5
pred_honest <- ggpredict(model_pooled, terms = c("rel_honest [1,5]", "year"))

# PID: 1 → 7
pred_pid <- ggpredict(model_pooled, terms = c("pid [1,7]", "year"))

# Inspect the results
pred_immig
pred_comp
pred_honest
pred_pid


#---plot AMEs -dots and whiskers---pooled 2020 and 2024 difference
library(ggplot2)

ame_df <- data.frame(
  Predictor = rep(c("Immigration Ideology", "Relative Competence",
                    "Relative Honesty", "PID"), each = 2),
  Year = rep(c("2020", "2024"), times = 4),
  AME = c(-0.008, -0.007,
          -0.033, -0.024,
          -0.017, -0.015,
          -0.025, -0.016),
  SE = c(0.005, 0.003,
         0.005, 0.004,
         0.011, 0.007,
         0.007, 0.005)
)

ame_df <- ame_df %>%
  mutate(Lower = AME - 1.96 * SE,
         Upper = AME + 1.96 * SE)

ggplot(ame_df, aes(x = AME, y = Predictor, color = Year)) +
  geom_point(position = position_dodge(width = 0.6), size = 3) +
  geom_errorbarh(aes(xmin = Lower, xmax = Upper),
                 position = position_dodge(width = 0.6), height = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "gray50") +
  labs(x = "Average Marginal Effect on Pr(Democratic Vote)",
       y = "", color = "Election Year",
       title = "AMEs of Immigration, PID, and Valence Predictors") +
  theme_minimal(base_size = 14)
